package com.qying.jvm.classloader;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
import java.util.concurrent.TimeUnit;

public class Hello {
    public Hello() {
    }

    public void test() {
        System.out.println(System.currentTimeMillis() + " => hello world");

    }

    public static void main(String[] args) {
        Random random = new Random();
        double randomScore = 1000 * random.nextDouble();
        System.out.println(randomScore);
    }

}

class MyClassLoader extends ClassLoader {
    public static void main(String[] args) throws Exception {
        MyClassLoader m = new MyClassLoader();

        Class clazz1 = m.loadClass("com.qying.jvm.classloader.Hello");

        clazz1.getDeclaredMethod("test").invoke(clazz1.getDeclaredConstructor().newInstance());

        while (true) {
            TimeUnit.SECONDS.sleep(5);

            m = new MyClassLoader();

            Class clazz2 = m.loadClass("com.qying.jvm.classloader.Hello");

            clazz2.getDeclaredMethod("test").invoke(clazz2.getDeclaredConstructor().newInstance());

            System.out.println("Class1 == class2 :" + (clazz1 == clazz2));

        }
        /*Class clazz1 = MyClassLoader.class.getClassLoader().loadClass("com.qying.jvm.classloader.Hello");

        clazz1.getDeclaredMethod("test").invoke(clazz1.getDeclaredConstructor().newInstance());

        while (true) {
            TimeUnit.SECONDS.sleep(5);

            m = new MyClassLoader();

            Class clazz2 = MyClassLoader.class.getClassLoader().loadClass("com.qying.jvm.classloader.Hello");

            clazz2.getDeclaredMethod("test").invoke(clazz2.getDeclaredConstructor().newInstance());

            System.out.println("Class1 == class2 :" + (clazz1 == clazz2));

        }*/

    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        String path = "C:\\gomeSoft\\qying-rpc\\qying-study\\target\\classes" + name.replace('.', '/') + ".class";

        File f = new File(path);
        if (!f.exists()) {
            return super.loadClass(name);

        }

        try {
            InputStream is = new FileInputStream(f);

            byte[] b = new byte[is.available()];

            is.read(b);

            return defineClass(name, b, 0, b.length);

        } catch (IOException e) {
            e.printStackTrace();

        }

        return null;

    }

}